package com.settlement.system.handler.xxljob;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.model.QyWechatData;
import com.settlement.system.common.util.HttpUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.model.entity.OdsErpRetailSalesOrderMain;
import com.settlement.system.model.entity.OdsOmsRetailSalesOrderDetails;
import com.settlement.system.model.entity.OdsOmsRetailSalesOrderMain;
import com.settlement.system.model.query.OdsOmsRetailSalesOrderMainQuery;
import com.settlement.system.service.*;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
@RequiredArgsConstructor
public class MudiBaiShengHandler {

    private static final Logger logger = LoggerFactory.getLogger(MudiBaiShengHandler.class);

    @Value("${system.config.address}")
    private String settlementUrl;

    private final OdsOmsRetailSalesOrderMainService odsOmsRetailSalesOrderMainService;

    private final OdsOmsRetailSalesOrderDetailsService odsOmsRetailSalesOrderDetailsService;

    private final OdsErpRetailSalesOrderMainService odsErpRetailSalesOrderMainService;

    private final OdsOmsRetailReturnOrderMainService odsOmsRetailReturnOrderMainService;

    private final OdsOmsRetailReturnOrderDetailsService odsOmsRetailReturnOrderDetailsService;

    private final OdsOmsShopService odsOmsShopService;

    // 上一次推送时间
    private static LocalDateTime lastNotifyTime;
    private static LocalDateTime returnLastNotifyTime;

    @XxlJob("bsOmsOrderJobHandler")
    public void bsOmsOrderJobHandler() {
        // 格式为： 2022-01-01 00:00:00,2022-01-01 00:01:00#店铺ID
        // long jobId = XxlJobHelper.getJobId();
        // 设置5秒的连接超时和10秒的读取超时
        // XxlJobApi xxlJobApi = Feign.builder().decoder(new JacksonDecoder()).options(new feign.Request.Options(5000, 10000)).target(XxlJobApi.class, xxlJobUrl);
        // 通过JobId获取Job详情
        // ReturnT<XxlJobInfo> info = xxlJobApi.getInfo(String.valueOf(jobId));
        String jobParam = XxlJobHelper.getJobParam().strip();
        // 如果参数为空，则按照约定的规则提取数据，如果有值，就按照时间段来提取数据
        LocalDateTime start;
        LocalDateTime end;
        String storeId = null;
        if (StringUtils.hasText(jobParam)) {
            if (jobParam.contains("#")) {
                String[] array = jobParam.split("#");
                String[] dates = array[0].split(",");
                start = LocalDateTime.parse(dates[0].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                end = LocalDateTime.parse(dates[1].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                // 店铺ID
                storeId = array[1].strip();
            } else {
                String[] dates = jobParam.split(",");
                start = LocalDateTime.parse(dates[0].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                end = LocalDateTime.parse(dates[1].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        } else {
            start = LocalDateTime.now().toLocalDate().atStartOfDay().minusDays(1);
            end = LocalDateTime.now().toLocalDate().atStartOfDay();
        }
        List<DateItem> dateItemList = new ArrayList<>();
        // 组装日期列表
        while (start.plusDays(1).isBefore(end)) {
            DateItem dateItem = new DateItem();
            dateItem.setStartTime(start);
            dateItem.setEndTime(start.plusDays(1));
            dateItemList.add(dateItem);
            start = start.plusDays(1);
        }
        if (Objects.nonNull(storeId)) {
            logger.info("过滤店铺编码：【%s】".formatted(storeId));
        } else {
            logger.info("不进行店铺过滤");
        }
        // 加上最后一个时间段
        dateItemList.add(new DateItem(start, end));
        logger.info("开始时间：{}", dateItemList.get(0).getStartTime());
        logger.info("结束时间：{}", end);
        XxlJobApi xxlJobApi = Feign.builder().encoder(new JacksonEncoder()).decoder(new JacksonDecoder()).options(new feign.Request.Options(5000, 10000)).target(XxlJobApi.class, settlementUrl);
        OdsOmsRetailSalesOrderMainQuery queryParams;
        List<OdsOmsRetailSalesOrderMain> records;
        OdsOmsRetailSalesOrderDetails details;
        OdsOmsRetailSalesOrderMain record;
        List<OdsOmsRetailSalesOrderDetails> orderDetails;
        OdsErpRetailSalesOrderMain odsErpRetailSalesOrderMain;
        List<OdsErpRetailSalesOrderMain> salesOrderMains;
        OdsErpRetailSalesOrderMain salesOrderMain;
        Map<String, String> dataMap;
        List<Map<String, String>> dataList;
        ReturnT<XxlJobInfo> returnT;
        for (DateItem dateItem : dateItemList) {
            queryParams = new OdsOmsRetailSalesOrderMainQuery();
            queryParams.setShippingTimeFhStart(dateItem.getStartTime());
            queryParams.setShippingTimeFhEnd(dateItem.getEndTime());
            if (Objects.nonNull(storeId)) {
                queryParams.setSdId(Long.valueOf(storeId));
            }
            queryParams.setPageSize(200);
            Page<OdsOmsRetailSalesOrderMain> page = odsOmsRetailSalesOrderMainService.getPage(queryParams);
            logger.info("查询到{}页数据", page.getPages());
            while (page.getRecords().size() > 0) {
                logger.info("正在处理时间段：【%s】-【%s】".formatted(dateItem.getStartTime(), dateItem.getEndTime()));
                dataList = new ArrayList<>();
                logger.info("当前页：{}, 总页数：{}", page.getCurrent(), page.getPages());
                records = page.getRecords();
                List<String> orderNoSnList = records.stream().map(OdsOmsRetailSalesOrderMain::getOrderSn).distinct().toList();
                details = new OdsOmsRetailSalesOrderDetails();
                if (orderNoSnList.size() > 0) {
                    details.setOrderSnList(orderNoSnList);
                    orderDetails = odsOmsRetailSalesOrderDetailsService.getList(details);
                    logger.info("一共【{}】条数据", orderDetails.size());
                    odsErpRetailSalesOrderMain = new OdsErpRetailSalesOrderMain();
                    odsErpRetailSalesOrderMain.setYdjhList(orderNoSnList);
                    salesOrderMains = odsErpRetailSalesOrderMainService.getList(odsErpRetailSalesOrderMain);
                    for (OdsOmsRetailSalesOrderDetails orderDetail : orderDetails) {
                        record = records.stream().filter(item -> Objects.equals(item.getOrderSn(), orderDetail.getOrderSn())).findFirst().orElse(null);
                        if (Objects.nonNull(record)) {
                            dataMap = new HashMap<>();
                            // 订单号
                            dataMap.put("orderNo", record.getOrderSn());
                            // 平台唯一ID
                            dataMap.put("pId", orderDetail.getLineNo());
                            // 店铺ID
                            dataMap.put("storeId", record.getSdId().toString());
                            // 网店交易号
                            dataMap.put("storeTradeNo", record.getDealCode());
                            // 原始交易号
                            dataMap.put("originalNo", orderDetail.getOriginalDealCode());
                            // 子交易号
                            dataMap.put("subNo", orderDetail.getSubDealCode());
                            // 订单状态
                            dataMap.put("status", Objects.isNull(record.getOrderStatus()) ? null : record.getOrderStatus().toString());
                            // 下单时间
                            dataMap.put("purchasedTime", Objects.isNull(record.getAddTime()) ? null : record.getAddTime().toString());
                            // 付款时间
                            dataMap.put("paymentTime", Objects.isNull(record.getPayTime()) ? null : record.getPayTime().toString());
                            // 发货时间
                            dataMap.put("sendTime", Objects.isNull(record.getShippingTimeFh()) ? null : record.getShippingTimeFh().toString());
                            // 已付金额
                            dataMap.put("paidAmount", Objects.isNull(record.getPayment()) ? BigDecimal.ZERO.toString() : record.getPayment().toString());
                            // 商品SKU
                            dataMap.put("sku", orderDetail.getSku());
                            // 商品名称
                            dataMap.put("productName", orderDetail.getGoodsName());
                            // 均摊金额
                            dataMap.put("equalizationAmount", Objects.isNull(orderDetail.getSharePayment()) ? BigDecimal.ZERO.toString() : orderDetail.getSharePayment().toString());
                            // 数量
                            dataMap.put("qty", Objects.isNull(orderDetail.getGoodsNumber()) ? "0" : orderDetail.getGoodsNumber().toString());
                            // 支付状态
                            dataMap.put("payStatus", Objects.isNull(record.getPayStatus()) ? null : record.getPayStatus().toString());
                            // 发货仓库
                            dataMap.put("sendWarehouse", Objects.isNull(record.getFhckmc()) ? null : record.getFhckmc().toString());
                            // 订单转入时间
                            dataMap.put("inTime", Objects.isNull(record.getTransTime()) ? null : record.getTransTime().toString());
                            // 订单确认时间
                            dataMap.put("confirmTime", Objects.isNull(record.getConfirmTime()) ? null : record.getConfirmTime().toString());
                            // 通知配货时间
                            dataMap.put("noticeTime", Objects.isNull(record.getShippingTimeTzph()) ? null : record.getShippingTimeTzph().toString());
                            // 出库时间
                            dataMap.put("outTime", Objects.isNull(record.getShippingTimeCk()) ? null : record.getShippingTimeCk().toString());
                            // 客户留言
                            dataMap.put("customerMessage", record.getBuyMsg());
                            // 商家备注
                            dataMap.put("sellerRemark", record.getSellerMsg());
                            // 订单备注
                            dataMap.put("orderRemark", record.getOrderMsg());
                            // 物流单号
                            dataMap.put("deliveryNo", record.getShippingSn());
                            // 商品金额
                            dataMap.put("goodsAmount", Objects.isNull(orderDetail.getGoodsPrice()) ? null : orderDetail.getGoodsPrice().toString());
                            // 商品标记
                            dataMap.put("goodsTag", Objects.isNull(orderDetail.getIsGift()) ? null : orderDetail.getIsGift().toString());
                            // 平台商品ID
                            dataMap.put("goodsId", Objects.isNull(orderDetail.getNumIid()) ? null : orderDetail.getNumIid().toString());
                            // 实际支付金额（去除平台优惠）
                            dataMap.put("actPayAmount", Objects.isNull(record.getPayment()) ? null : record.getPayment().toString());
                            // 品牌
                            dataMap.put("brandName", orderDetail.getBrandName());
                            String orderNoSn = record.getOrderSn();
                            // ERP单号
                            salesOrderMain = salesOrderMains.stream().filter(item -> Objects.equals(item.getYdjh(), orderNoSn)).findFirst().orElse(null);
                            if (Objects.nonNull(salesOrderMain)) {
                                dataMap.put("erpNo", salesOrderMain.getDjbh());
                            }
                            dataList.add(dataMap);
                        }
                    }
                    for (int i = 0; i < 3; i++) {
                        // 推送
                        try {
                            logger.info("推送订单数据：{}", dataList.stream().map(item -> item.get("pId")).toList());
                            returnT = xxlJobApi.apiPost(0, dataList);
                            logger.info("推送订单结果：{}", returnT);
                            break;
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 推送信息 跟当前时间比较，小于30秒不重复推送
                            LocalDateTime now = LocalDateTime.now();
                            if (Objects.isNull(lastNotifyTime) || Math.abs(Duration.between(now, lastNotifyTime).getSeconds()) > 30) {
                                if (i >= 2) {
                                    // 当前尝试次数超过2次，发送通知
                                    String content = "%s提醒：\n推送订单数据到结算系统失败。\n".formatted("慕迪百盛OMS") +
                                            "失败原因：<font color=\"comment\">%s</font>\n".formatted(e.getMessage()) +
                                            "数据范围：<font color=\"comment\">%s,%s</font>\n".formatted(dateItem.getStartTime().toString().replace("T", " "), dateItem.getEndTime().toString().replace("T", " ")) +
                                            "页码：<font color=\"comment\">%s页</font>\n".formatted(queryParams.getPageNum()) +
                                            "<font color=\"warning\">请立即查看</font>\n";
                                    QyWechatData params = QyWechatData.Markdown(content);
                                    for (int j = 0; j < 3; j++) {
                                        try {
                                            HttpUtils.sendToQyWechat(params);
                                            break;
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                                // 记录推送时间
                                lastNotifyTime = now;
                            }
                            try {
                                logger.info("5秒后尝试重新推送...");
                                Thread.sleep(5000);
                            } catch (Exception ignored) {
                            }
                        }
                    }
                }
                try {
                    logger.info("等待下一个5秒再推送...");
                    Thread.sleep(5000);
                } catch (Exception ignored) {
                }
                // 查下一页
                queryParams.setPageNum(queryParams.getPageNum() + 1);
                page = odsOmsRetailSalesOrderMainService.getPage(queryParams);
            }
        }
    }

    @XxlJob("fixBsOmsOrderJobHandler")
    public void fixBsOmsOrderJobHandler() {
        // 格式为： 2022-01-01 00:00:00,2022-01-01 00:01:00#店铺ID
        // long jobId = XxlJobHelper.getJobId();
        // 设置5秒的连接超时和10秒的读取超时
        // XxlJobApi xxlJobApi = Feign.builder().decoder(new JacksonDecoder()).options(new feign.Request.Options(5000, 10000)).target(XxlJobApi.class, xxlJobUrl);
        // 通过JobId获取Job详情
        // ReturnT<XxlJobInfo> info = xxlJobApi.getInfo(String.valueOf(jobId));
        String jobParam = XxlJobHelper.getJobParam().strip();
        // 如果参数为空，则按照约定的规则提取数据，如果有值，就按照时间段来提取数据
        LocalDateTime start;
        LocalDateTime end;
        String storeId = null;
        if (StringUtils.hasText(jobParam)) {
            if (jobParam.contains("#")) {
                String[] strings = jobParam.split("#");
                String[] dates = strings[0].split(",");
                start = LocalDateTime.parse(dates[0].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                end = LocalDateTime.parse(dates[1].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                // 截取出店铺ID
                storeId = strings[1].strip();
            } else {
                String[] dates = jobParam.split(",");
                start = LocalDateTime.parse(dates[0].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                end = LocalDateTime.parse(dates[1].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        } else {
            start = LocalDateTime.now().toLocalDate().atStartOfDay().minusDays(1);
            end = LocalDateTime.now().toLocalDate().atStartOfDay();
        }
        List<DateItem> dateItemList = new ArrayList<>();
        // 组装日期列表
        while (start.plusDays(1).isBefore(end)) {
            DateItem dateItem = new DateItem();
            dateItem.setStartTime(start);
            dateItem.setEndTime(start.plusDays(1));
            dateItemList.add(dateItem);
            start = start.plusDays(1);
        }
        if (Objects.nonNull(storeId)) {
            logger.info("过滤店铺：【%s】".formatted(storeId));
        }
        // 加上最后一个时间段
        dateItemList.add(new DateItem(start, end));
        logger.info("开始时间：{}", dateItemList.get(0).getStartTime());
        logger.info("结束时间：{}", end);
        XxlJobApi xxlJobApi = Feign.builder().encoder(new JacksonEncoder()).decoder(new JacksonDecoder()).options(new feign.Request.Options(5000, 10000)).target(XxlJobApi.class, settlementUrl);
        OdsOmsRetailSalesOrderMainQuery queryParams;
        List<OdsOmsRetailSalesOrderMain> records;
        OdsOmsRetailSalesOrderDetails details;
        OdsOmsRetailSalesOrderMain record;
        List<OdsOmsRetailSalesOrderDetails> orderDetails;
        OdsErpRetailSalesOrderMain odsErpRetailSalesOrderMain;
        List<OdsErpRetailSalesOrderMain> salesOrderMains;
        OdsErpRetailSalesOrderMain salesOrderMain;
        Map<String, String> dataMap;
        List<Map<String, String>> dataList;
        ReturnT<XxlJobInfo> returnT;
        for (DateItem dateItem : dateItemList) {
            queryParams = new OdsOmsRetailSalesOrderMainQuery();
            queryParams.setShippingTimeFhStart(dateItem.getStartTime());
            queryParams.setShippingTimeFhEnd(dateItem.getEndTime());
            if (Objects.nonNull(storeId)) {
                queryParams.setSdId(Long.valueOf(storeId));
            }
            queryParams.setPageSize(200);
            Page<OdsOmsRetailSalesOrderMain> page = odsOmsRetailSalesOrderMainService.getPage(queryParams);
            logger.info("查询到{}页数据", page.getPages());
            while (page.getRecords().size() > 0) {
                logger.info("正在处理时间段：【%s】-【%s】".formatted(dateItem.getStartTime(), dateItem.getEndTime()));
                dataList = new ArrayList<>();
                logger.info("当前页：{}, 总页数：{}", page.getCurrent(), page.getPages());
                records = page.getRecords();
                List<String> orderNoSnList = records.stream().map(OdsOmsRetailSalesOrderMain::getOrderSn).distinct().toList();
                details = new OdsOmsRetailSalesOrderDetails();
                if (orderNoSnList.size() > 0) {
                    details.setOrderSnList(orderNoSnList);
                    orderDetails = odsOmsRetailSalesOrderDetailsService.getList(details);
                    logger.info("一共【{}】条数据", orderDetails.size());
                    odsErpRetailSalesOrderMain = new OdsErpRetailSalesOrderMain();
                    odsErpRetailSalesOrderMain.setYdjhList(orderNoSnList);
                    salesOrderMains = odsErpRetailSalesOrderMainService.getList(odsErpRetailSalesOrderMain);
                    for (OdsOmsRetailSalesOrderDetails orderDetail : orderDetails) {
                        record = records.stream().filter(item -> Objects.equals(item.getOrderSn(), orderDetail.getOrderSn())).findFirst().orElse(null);
                        if (Objects.nonNull(record)) {
                            dataMap = new HashMap<>();
                            // 订单号
                            dataMap.put("orderNo", record.getOrderSn());
                            // 平台唯一ID
                            dataMap.put("pId", orderDetail.getLineNo());
                            // 店铺ID
                            dataMap.put("storeId", record.getSdId().toString());
                            // 网店交易号
                            dataMap.put("storeTradeNo", record.getDealCode());
                            // 原始交易号
                            dataMap.put("originalNo", orderDetail.getOriginalDealCode());
                            // 子交易号
                            dataMap.put("subNo", orderDetail.getSubDealCode());
                            // 订单状态
                            dataMap.put("status", Objects.isNull(record.getOrderStatus()) ? null : record.getOrderStatus().toString());
                            // 下单时间
                            dataMap.put("purchasedTime", Objects.isNull(record.getAddTime()) ? null : record.getAddTime().toString());
                            // 付款时间
                            dataMap.put("paymentTime", Objects.isNull(record.getPayTime()) ? null : record.getPayTime().toString());
                            // 发货时间
                            dataMap.put("sendTime", Objects.isNull(record.getShippingTimeFh()) ? null : record.getShippingTimeFh().toString());
                            // 已付金额
                            dataMap.put("paidAmount", Objects.isNull(record.getPayment()) ? BigDecimal.ZERO.toString() : record.getPayment().toString());
                            // 商品SKU
                            dataMap.put("sku", orderDetail.getSku());
                            // 商品名称
                            dataMap.put("productName", orderDetail.getGoodsName());
                            // 均摊金额
                            dataMap.put("equalizationAmount", Objects.isNull(orderDetail.getSharePayment()) ? BigDecimal.ZERO.toString() : orderDetail.getSharePayment().toString());
                            // 数量
                            dataMap.put("qty", Objects.isNull(orderDetail.getGoodsNumber()) ? "0" : orderDetail.getGoodsNumber().toString());
                            // 支付状态
                            dataMap.put("payStatus", Objects.isNull(record.getPayStatus()) ? null : record.getPayStatus().toString());
                            // 发货仓库
                            dataMap.put("sendWarehouse", Objects.isNull(record.getFhckmc()) ? null : record.getFhckmc().toString());
                            // 订单转入时间
                            dataMap.put("inTime", Objects.isNull(record.getTransTime()) ? null : record.getTransTime().toString());
                            // 订单确认时间
                            dataMap.put("confirmTime", Objects.isNull(record.getConfirmTime()) ? null : record.getConfirmTime().toString());
                            // 通知配货时间
                            dataMap.put("noticeTime", Objects.isNull(record.getShippingTimeTzph()) ? null : record.getShippingTimeTzph().toString());
                            // 出库时间
                            dataMap.put("outTime", Objects.isNull(record.getShippingTimeCk()) ? null : record.getShippingTimeCk().toString());
                            // 客户留言
                            dataMap.put("customerMessage", record.getBuyMsg());
                            // 商家备注
                            dataMap.put("sellerRemark", record.getSellerMsg());
                            // 订单备注
                            dataMap.put("orderRemark", record.getOrderMsg());
                            // 物流单号
                            dataMap.put("deliveryNo", record.getShippingSn());
                            // 商品金额
                            dataMap.put("goodsAmount", Objects.isNull(orderDetail.getGoodsPrice()) ? null : orderDetail.getGoodsPrice().toString());
                            // 商品标记
                            dataMap.put("goodsTag", Objects.isNull(orderDetail.getIsGift()) ? null : orderDetail.getIsGift().toString());
                            // 平台商品ID
                            dataMap.put("goodsId", Objects.isNull(orderDetail.getNumIid()) ? null : orderDetail.getNumIid().toString());
                            // 实际支付金额（去除平台优惠）
                            dataMap.put("actPayAmount", Objects.isNull(record.getPayment()) ? null : record.getPayment().toString());
                            // 品牌
                            dataMap.put("brandName", orderDetail.getBrandName());
                            String orderNoSn = record.getOrderSn();
                            // ERP单号
                            salesOrderMain = salesOrderMains.stream().filter(item -> Objects.equals(item.getYdjh(), orderNoSn)).findFirst().orElse(null);
                            if (Objects.nonNull(salesOrderMain)) {
                                dataMap.put("erpNo", salesOrderMain.getDjbh());
                            }
                            dataList.add(dataMap);
                        }
                    }
                    for (int i = 0; i < 3; i++) {
                        // 推送
                        try {
                            logger.info("推送订单数据：{}", dataList.stream().map(item -> item.get("pId")).toList());
                            returnT = xxlJobApi.fixOrderData(dataList);
                            logger.info("推送订单结果：{}", returnT);
                            break;
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 推送信息 跟当前时间比较，小于30秒不重复推送
                            LocalDateTime now = LocalDateTime.now();
                            if (Objects.isNull(lastNotifyTime) || Math.abs(Duration.between(now, lastNotifyTime).getSeconds()) > 30) {
                                if (i >= 2) {
                                    // 当前尝试次数超过2次，发送通知
                                    String content = "%s提醒：\n推送订单数据到结算系统失败。\n".formatted("慕迪百盛OMS") +
                                            "失败原因：<font color=\"comment\">%s</font>\n".formatted(e.getMessage()) +
                                            "数据范围：<font color=\"comment\">%s,%s</font>\n".formatted(dateItem.getStartTime().toString().replace("T", " "), dateItem.getEndTime().toString().replace("T", " ")) +
                                            "页码：<font color=\"comment\">%s页</font>\n".formatted(queryParams.getPageNum()) +
                                            "<font color=\"warning\">请立即查看</font>\n";
                                    QyWechatData params = QyWechatData.Markdown(content);
                                    for (int j = 0; j < 3; j++) {
                                        try {
                                            HttpUtils.sendToQyWechat(params);
                                            break;
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                                // 记录推送时间
                                lastNotifyTime = now;
                            }
                            try {
                                logger.info("5秒后尝试重新推送...");
                                Thread.sleep(5000);
                            } catch (Exception ignored) {
                            }
                        }
                    }
                }
                try {
                    logger.info("等待下一个5秒再推送...");
                    Thread.sleep(5000);
                } catch (Exception ignored) {
                }
                // 查下一页
                queryParams.setPageNum(queryParams.getPageNum() + 1);
                page = odsOmsRetailSalesOrderMainService.getPage(queryParams);
            }
        }
    }

    @XxlJob("bsOmsReturnOrderJobHandler")
    public void bsOmsReturnOrderJobHandler() {
        logger.info("定时任务代码已注释");
        /*String jobParam = XxlJobHelper.getJobParam().strip();
        // 如果参数为空，则按照约定的规则提取数据，如果有值，就按照时间段来提取数据
        // 格式为： 2022-01-01 00:00:00,2022-01-01 00:0:00
        LocalDateTime start;
        LocalDateTime end;
        if (StringUtils.hasText(jobParam)) {
            String[] dates = jobParam.split(",");
            start = LocalDateTime.parse(dates[0].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            end = LocalDateTime.parse(dates[1].strip(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            start = LocalDateTime.now().toLocalDate().atStartOfDay().minusDays(1);
            end = LocalDateTime.now().toLocalDate().atStartOfDay();
        }
        List<DateItem> dateItemList = new ArrayList<>();
        // 组装日期列表
        while (start.plusDays(1).isBefore(end)) {
            DateItem dateItem = new DateItem();
            dateItem.setStartTime(start);
            dateItem.setEndTime(start.plusDays(1));
            dateItemList.add(dateItem);
            start = start.plusDays(1);
        }
        // 加上最后一个时间段
        dateItemList.add(new DateItem(start, end));
        logger.info("开始时间：{}", start);
        logger.info("结束时间：{}", end);
        OdsOmsRetailReturnOrderMainQuery queryParams;
        OdsOmsRetailReturnOrderDetails odsOmsRetailReturnOrderDetails;
        List<OdsOmsRetailReturnOrderDetails> serviceList;
        OdsOmsRetailReturnOrderMain orderMain;
        Map<String, String> dataMap;
        ReturnT<XxlJobInfo> returnT;
        List<Map<String, String>> dataList;
        List<OdsOmsShop> omsShopList;
        OdsOmsShop odsOmsShop;
        XxlJobApi xxlJobApi = Feign.builder().encoder(new JacksonEncoder()).decoder(new JacksonDecoder()).options(new feign.Request.Options(5000, 10000)).target(XxlJobApi.class, settlementUrl);
        for (DateItem dateItem : dateItemList) {
            queryParams = new OdsOmsRetailReturnOrderMainQuery();
            queryParams.setPageSize(200);
            queryParams.setAddTimeStart(dateItem.getStartTime());
            queryParams.setAddTimeEnd(dateItem.getEndTime());
            Page<OdsOmsRetailReturnOrderMain> servicePage = odsOmsRetailReturnOrderMainService.getPage(queryParams);
            logger.info("查询到{}页数据", servicePage.getPages());
            while (servicePage.getRecords().size() > 0) {
                logger.info("正在处理时间段：【%s】-【%s】".formatted(dateItem.getStartTime(), dateItem.getEndTime()));
                logger.info("当前页：{}, 总页数：{}", servicePage.getCurrent(), servicePage.getPages());
                dataList = new ArrayList<>();
                List<String> returnOrderSnList = servicePage.getRecords().stream().map(OdsOmsRetailReturnOrderMain::getReturnOrderSn).distinct().toList();
                List<String> sdCodeList = servicePage.getRecords().stream().map(OdsOmsRetailReturnOrderMain::getSdCode).distinct().toList();
                omsShopList = odsOmsShopService.list(new LambdaQueryWrapper<OdsOmsShop>().in(OdsOmsShop::getKhdm, sdCodeList));
                odsOmsRetailReturnOrderDetails = new OdsOmsRetailReturnOrderDetails();
                odsOmsRetailReturnOrderDetails.setReturnOrderSnList(returnOrderSnList);
                serviceList = odsOmsRetailReturnOrderDetailsService.getList(odsOmsRetailReturnOrderDetails);
                for (OdsOmsRetailReturnOrderDetails omsRetailReturnOrderDetails : serviceList) {
                    orderMain = servicePage.getRecords().stream().filter(item -> Objects.equals(item.getReturnOrderSn(), omsRetailReturnOrderDetails.getReturnOrderSn())).findFirst().orElse(null);
                    if (Objects.nonNull(orderMain)) {
                        String sdCode = orderMain.getSdCode();
                        odsOmsShop = omsShopList.stream().filter(item -> Objects.equals(item.getKhdm(), sdCode)).findFirst().orElse(null);
                        if (Objects.isNull(odsOmsShop)) {
                            continue;
                        }
                        dataMap = new HashMap<>();
                        // 平台唯一ID
                        dataMap.put("pId", omsRetailReturnOrderDetails.getLineNo().toString());
                        // 退货编号
                        dataMap.put("returnNo", omsRetailReturnOrderDetails.getReturnOrderSn());
                        // 店铺ID
                        dataMap.put("storeId", odsOmsShop.getId());
                        // 关联订单号
                        dataMap.put("linkNo", orderMain.getRelatingOrderSn());
                        // 退货交易号
                        dataMap.put("returnTradeNo", orderMain.getRefundDealCode());
                        // 退货类型
                        dataMap.put("returnType", Objects.isNull(orderMain.getReturnOrderType()) ? null : orderMain.getReturnOrderType().toString());
                        // 订单状态
                        dataMap.put("status", Objects.isNull(orderMain.getReturnOrderStatus()) ? null : orderMain.getReturnOrderStatus().toString());
                        // 退货创建时间
                        dataMap.put("returnTime", Objects.isNull(orderMain.getAddTime()) ? null : orderMain.getAddTime().toString());
                        // 入库时间
                        dataMap.put("storageTime", Objects.isNull(orderMain.getReturnShippingTimeRk()) ? null : orderMain.getReturnShippingTimeRk().toString());
                        // 品牌
                        dataMap.put("brand", omsRetailReturnOrderDetails.getBrandName());
                        // 商品名称
                        dataMap.put("productName", omsRetailReturnOrderDetails.getGoodsName());
                        // 条码（商品SKU）
                        dataMap.put("productCode", omsRetailReturnOrderDetails.getSku());
                        // 数量
                        dataMap.put("qty", Objects.isNull(omsRetailReturnOrderDetails.getGoodsNumberReturnSj()) ? "0" : omsRetailReturnOrderDetails.getGoodsNumberReturnSj().toString());
                        // 实退金额小计
                        dataMap.put("returnAmount", Objects.isNull(omsRetailReturnOrderDetails.getSharePayment()) ? BigDecimal.ZERO.toString() : omsRetailReturnOrderDetails.getSharePayment().toString());
                        // 平台退单编号
                        dataMap.put("refundCode", orderMain.getRefundCode());
                        // PO
                        dataMap.put("po", omsRetailReturnOrderDetails.getPoNo());
                        dataList.add(dataMap);
                    }
                }
                for (int i = 0; i < 3; i++) {
                    // 推送
                    try {
                        logger.info("推送退货单数据：{}", dataList.stream().map(item -> item.get("pId")).toList());
                        returnT = xxlJobApi.apiPost(1, dataList);
                        logger.info("推送退货单结果：{}", returnT);
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 推送信息 跟当前时间比较，小于30秒不重复推送
                        LocalDateTime now = LocalDateTime.now();
                        if (Objects.isNull(returnLastNotifyTime) || Math.abs(Duration.between(now, returnLastNotifyTime).getSeconds()) > 30) {
                            if (i >= 2) {
                                // 当前尝试次数超过2次，发送通知
                                String content = "%s提醒：\n推送退货单数据到结算系统失败。\n".formatted("慕迪百盛OMS") +
                                        "失败原因：<font color=\"comment\">%s</font>\n".formatted(e.getMessage()) +
                                        "数据范围：<font color=\"comment\">%s,%s</font>\n".formatted(dateItem.getStartTime().toString().replace("T", " "), dateItem.getEndTime().toString().replace("T", " ")) +
                                        "页码：<font color=\"comment\">%s页</font>\n".formatted(queryParams.getPageNum()) +
                                        "<font color=\"warning\">请立即查看</font>\n";
                                QyWechatData params = QyWechatData.Markdown(content);
                                for (int j = 0; j < 3; j++) {
                                    try{
                                        HttpUtils.sendToQyWechat(params);
                                        break;
                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }
                            }
                            // 记录推送时间
                            returnLastNotifyTime = now;
                        }
                        try {
                            logger.info("5秒后尝试重新推送...");
                            Thread.sleep(5000);
                        } catch (Exception ignored) {
                        }
                    }
                }
                try {
                    logger.info("等待下一个5秒再推送...");
                    Thread.sleep(5000);
                } catch (Exception ignored) {
                }
                // 查下一页
                queryParams.setPageNum(queryParams.getPageNum() + 1);
                servicePage = odsOmsRetailReturnOrderMainService.getPage(queryParams);
            }
        }*/
    }
}
